package com.speed.controller;

import java.io.File;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.speed.entity.User;
import com.speed.service.UserService;
import com.speed.util.qc.MatrixToImageWriter;

public class UserController extends Controller {

	public void index() {
		System.out.println("----");
		
		try {
			renderJsp("login.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void login() {

		User user = getModel(User.class);
		String username = user.getStr(User.USER_NAME);
		String pw = user.getStr(User.PASSWORD);

		if (StrKit.isBlank(username) || StrKit.isBlank(pw)) {
			renderJsp("/login.jsp");
			return;
		}

		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, pw, true);
		// 当前用户
		Subject currUser = SecurityUtils.getSubject();

		// 抛出的异常处理是用于转发到所需提示的页面
		try {
			currUser.login(usernamePasswordToken);
			String authority = username.equals("admin") ? "1" : "0";
			getSession().setAttribute("authority", authority);
		} catch (UnknownAccountException uae) {
			System.out.println(uae);
			setAttr("msgName", "请输入正确的用户名称");
			setAttr("msgPw", "请输入正确的用户密码");
			forwardAction("/user/index");
			return;
		} catch (IncorrectCredentialsException ice) {
			System.out.println(ice);
			setAttr("msgName", "请输入正确的用户名称");
			setAttr("msgPw", "请输入正确的用户密码");
			forwardAction("/user/index");
			return;
		} catch (LockedAccountException lae) {
			System.out.println(lae);
			setAttr("msgName", "请输入正确的用户名称");
			setAttr("msgPw", "请输入正确的用户密码");
			forwardAction("/user/index");
			return;
		} catch (AuthenticationException ae) {
			System.out.println(ae);
			setAttr("msgName", "请输入正确的用户名称");
			setAttr("msgPw", "请输入正确的用户密码");
			forwardAction("/user/index");
			return;
		}
		getSession().setAttribute("user", user);
		renderJsp("/index.jsp");
	}

//	public void genImg() {
//		String mobile = getPara("mobile");
//		String signCode = getPara("signCode");
//		try {
//			MatrixToImageWriter.genCode(signCode, mobile,
//					PathKit.getWebRootPath() + File.separator + "code" + File.separator + mobile + ".jpg");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		renderText("111111111111111");
//	}

}
